#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <stdlib.h>

int main()
{
  int pipe_fd[2] = {0};
  if(pipe(pipe_fd) < 0)
  {
    perror("pipe");
    return 1;
  }
  printf("%d, %d\n", pipe_fd[0], pipe_fd[1]);
  
  pid_t id = fork();
  if(id < 0)
  {
    perror("fork");
    return 2;
  }
  else if(id == 0)
  {
    //child write
    close(pipe_fd[0]); 
    const char* msg = "hello parent, I am child!";
    int count = 5;
    while(count)
    {
      write(pipe_fd[1], msg, strlen(msg));
      sleep(1);
      count--;
    }
    close(pipe_fd[1]);
    exit(0);
  }
  else 
  {
    //parent read
    close(pipe_fd[1]);
    char buffer[64];
    while(1)
    {
      buffer[0] = 0;
      ssize_t size = read(pipe_fd[0], buffer, sizeof(buffer) - 1);
      if(size > 0)
      {
        buffer[size] = 0;
        printf("parent get messge from child# %s\n", buffer);
      }
      else if(size == 0)
      {
        printf("pipe file close, child quit!\n");
        break;
      }
      else
      {
        //error
        break;
      }
    }
    int status = 0;
    if(waitpid(id, &status, 0) > 0)
    {
      printf("child quit, wait success!\n");
    }
    close(pipe_fd[0]);
  }
  return 0;
}
